﻿using System.Collections.Generic;
using Engine;
using Game;
using GameEntitySystem;

using TemplatesDatabase;

public class ComponentSummonee : ComponentFrame, IUpdateable
{
    public ulong m_ID;

    public ulong m_lordID;

    public ComponentSummoner m_lord;

    public SubsystemSummon m_subsystemSummon;

    public Game.Random m_random = new Game.Random();

    public Vector3 m_velocity;

    public Quaternion m_angularVelocity;

    public float m_flySpeed;

    public List<ComponentSummoneeBehavior> m_behaviors = new List<ComponentSummoneeBehavior>();

    // VectorFromLord属性使用表达式体写法
    public Vector3 VectorFromLord => m_lord.Position - Position;

    public UpdateOrder UpdateOrder => (UpdateOrder)2;




    public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
    {
        base.Load(valuesDictionary, idToEntityMap);
        if (valuesDictionary != null)
        {
            m_ID = valuesDictionary.GetValue<ulong>("ID", ((ulong)m_random.UInt() << 32) + (ulong)m_random.Int());
            m_lordID = valuesDictionary.GetValue<ulong>("LordID", 0uL);
            m_flySpeed = valuesDictionary.GetValue<float>("FlySpeed");
        }
        m_subsystemSummon = Project.FindSubsystem<SubsystemSummon>(true);
        foreach (ComponentSummoner summoner in m_subsystemSummon.m_summoners)
        {
            if (summoner.m_ID == m_lordID)
            {
                m_lord = summoner;
                m_lord.m_summonees.Add(this);
                m_subsystemSummon.m_summonees.Add(this);
            }
        }
    }

    public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
    {
        base.Save(valuesDictionary, entityToIdMap);
        valuesDictionary.SetValue<ulong>("ID", m_ID);
        valuesDictionary.SetValue<ulong>("LordID", m_lordID);
    }

    public void Update(float dt)
    {
        
       
        if (m_velocity.Length() > m_flySpeed)
        {
            m_velocity = m_flySpeed * Vector3.Normalize(m_velocity);
        }
       
        Position += m_velocity * dt;
        Rotation += m_angularVelocity * dt;
        ComponentSummoneeBehavior componentSummoneeBehavior = null;
        foreach (ComponentSummoneeBehavior behavior in m_behaviors)
        {
            if (behavior.IsActive && (componentSummoneeBehavior == null || (componentSummoneeBehavior).ImportanceLevel < behavior.ImportanceLevel))
            {
                componentSummoneeBehavior = behavior;
            }
        }
        componentSummoneeBehavior?.UpdateWhenActive(dt);
    }
}
